package ds.factcom.view.ui.item;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JTextField;

import ds.factcom.controller.invoice.InvoiceController;
import ds.factcom.exception.IsNotNumberException;
import ds.factcom.exception.NotExistDomainException;
import ds.factcom.view.ui.Messages;
import ds.factcom.view.validate.ValidatorClient;

@SuppressWarnings("serial")
public class ItemView extends JDialog {

	private JLabel prouctLabel;
	private JTextField productTF;
	private JLabel cantLabel;
	private JTextField cantTF;
	private JButton acceptBtn;
	private JButton cancelBtn;
	private final InvoiceController invoiceController;
	
	public ItemView(InvoiceController invoiceController) {
		this.invoiceController = invoiceController;
		initGUI();
	}

	private void initGUI() {
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		setTitle("Agregar Item");
		setSize(400, 100);
		setLocation(400, 300);
		setResizable(false);
		setModal(true);
		setLayout(new GridLayout(3,3));
		add(getProuctLabel());
		add(getProductTF());
		add(getCantLabel());
		add(getCantTF());
		add(getAcceptBtn());
		add(getCancelBtn());
	}

	public JLabel getProuctLabel() {
		if (prouctLabel == null) {
			prouctLabel = new JLabel("Producto");
		}
		return prouctLabel;
	}

	public JTextField getProductTF() {
		if (productTF == null) {
			productTF = new JTextField();
			productTF.setEnabled(false);
			productTF.setText(invoiceController.getProductDescription());
		}
		return productTF;
	}

	public JLabel getCantLabel() {
		if (cantLabel == null) {
			cantLabel = new JLabel("Cantidad");
		}
		return cantLabel;
	}

	public JTextField getCantTF() {
		if (cantTF == null) {
			cantTF = new JTextField();
			cantTF.setText("");
		}
		return cantTF;
	}
	
	public JButton getAcceptBtn() {
		if (acceptBtn == null) {
			acceptBtn = new JButton("Aceptar");
			acceptBtn.addActionListener(new ActionListener(){
				@Override
				public void actionPerformed(ActionEvent e) {
					try {
						String cant = getCantTF().getText();
						ValidatorClient.isNumber(cant);
						invoiceController.addProduct(getProductTF().getText(), Integer.valueOf(cant));
						ItemView.this.dispose();
					} catch (NotExistDomainException e1) {
						Messages.showErrorMessage(ItemView.this, e1.getMessage());
					} catch (IsNotNumberException e1) {
						Messages.showErrorMessage(ItemView.this, e1.getMessage());
					}
				}
			});
		}
		return acceptBtn;
	}

	public JButton getCancelBtn() {
		if (cancelBtn == null) {
			cancelBtn = new JButton("Cancelar");
			cancelBtn.addActionListener(new ActionListener(){
				@Override
				public void actionPerformed(ActionEvent e) {
					getCantTF().setText("");
				}
			});
		}
		return cancelBtn;
	}

	public void open() {
		setVisible(true);
	}
}
